import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import AddStudentDialog from './components/AddStudentDialog';
import SearchForm from './components/SearchForm';

import {
    Box,
    Typography,
    Button,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Paper,
    Pagination,
    Stack,
    Snackbar,
    Alert,
    CircularProgress,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle
} from '@mui/material';

import { UploadFile as UploadIcon, FileDownload as DownloadIcon, Add as AddIcon } from '@mui/icons-material';

import Breadcrumb, { BreadcrumbItem } from '../../components/Breadcrumb';
import PermissionGuard from '../../components/PermissionGuard';

import './Student.css';

import {
    searchStudents,
    addStudent,
    deleteStudent,
    uploadStudentFile,
    downloadStudentFile,
    getEnrollmentStatusOptions, getEnrollmentTypeOptions, getAdvisorOptions
} from '../../api';
import { StudentInfo, StudentSearchParams, AddStudentParams } from '../../api/types';

const Student = () => {
    const navigate = useNavigate();

    // 分页状态
    const [page, setPage] = useState(1);
    const [rowsPerPage] = useState(20);
    const [total, setTotal] = useState(0);

    // 加载状态
    const [loading, setLoading] = useState(false);

    // Snackbar状态
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'info' | 'warning' | 'error'>('success');

    // 添加学生对话框状态
    const [addDialogOpen, setAddDialogOpen] = useState(false);

    // 删除确认对话框状态
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [studentToDelete, setStudentToDelete] = useState<{ id: string; record_id: string; name: string } | null>(
        null
    );

    // 搜索字段
    const [searchParams, setSearchParams] = useState<StudentSearchParams>({
        record_id: '',
        sid: '',
        name: '',
        major: '',
        graduation_year: '',
        state: '',
        approach: '',
        difficulty: '',
        partner: '',
        limit: 20,
        page: 1
    });

    // 学籍状态选项状态
    const [enrollmentStatusOptions, setEnrollmentStatusOptions] = useState<string[]>([]);

    // 招生类型选项状态
    const [enrollmentTypeOptions, setEnrollmentTypeOptions] = useState<string[]>([]);

    // 顾问选项状态
    const [advisorOptions, setAdvisorOptions] = useState<string[]>([]);

    // 表格数据
    const [data, setData] = useState<StudentInfo[]>([]);

    // 面包屑路径
    const breadcrumbItems: BreadcrumbItem[] = [{ title: '首页' }, { title: '学生信息' }];

    // 加载数据
    const loadData = async (params: StudentSearchParams) => {
        setLoading(true);
        try {
            const response = await searchStudents(params);
            setData(response.detail);
            setTotal(response.total);
        } catch (error) {
            console.error('加载学生数据失败:', error);
            setSnackbarSeverity('error');
            setSnackbarMessage('加载数据失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            setLoading(false);
        }
    };

    // 初始化加载数据
    useEffect(() => {
        loadData({ ...searchParams, page: 1, limit: 20 });
        fetchEnrollmentStatusOptions(); // 获取学籍状态选项
        fetchEnrollmentTypeOptions(); // 获取学籍类型选项
        fetchAdvisorOptions(); // 获取顾问选项
    }, []);

    // 获取学籍状态选项
    const fetchEnrollmentStatusOptions = async () => {
        try {
            // 获取学籍状态选项列表
            const options = await getEnrollmentStatusOptions();
            console.log('Enrollment status options:', options);
            setEnrollmentStatusOptions(options);
        } catch (error) {
            console.error('获取学籍状态选项列表失败:', error);
            setEnrollmentStatusOptions([]);
        }
    };

    // 获取招生类型选项
    const fetchEnrollmentTypeOptions = async () => {
        try {
            // 获取招生类型选项列表
            const options = await getEnrollmentTypeOptions();
            console.log('Enrollment type options:', options);
            setEnrollmentTypeOptions(options);
        } catch (error) {
            console.error('获取招生类型选项列表失败:', error);
            setEnrollmentTypeOptions([]);
        }
    };

    // 获取顾问选项
    const fetchAdvisorOptions = async () => {
        try {
            // 获取顾问选项列表
            const options = await getAdvisorOptions();
            console.log('Advisor options:', options);
            setAdvisorOptions(options);
        } catch (error) {
            console.error('获取顾问选项列表失败:', error);
            setAdvisorOptions([]);
        }
    };

    // 处理搜索
    const handleSearch = (updatedParams: StudentSearchParams) => {
        setSearchParams(updatedParams);
        loadData(updatedParams);
    };

    // 处理添加
    const handleAdd = () => {
        // 打开添加学生对话框
        setAddDialogOpen(true);
    };

    // 处理学生信息提交
    const handleStudentSubmit = async (formData: AddStudentParams) => {
        try {
            setLoading(true);

            // 调用API添加学生信息
            const response = await addStudent(formData);

            console.log('学生信息添加成功:', response);

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage(`学生信息添加成功，学号: ${response.sid}, 记录ID: ${response.record_id}`);
            setSnackbarOpen(true);

            // 关闭对话框
            setAddDialogOpen(false);

            // 重新加载数据
            loadData(searchParams);
        } catch (error) {
            console.error('添加学生信息失败:', error);
            setSnackbarSeverity('error');
            setSnackbarMessage('添加学生信息失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            setLoading(false);
        }
    };

    // 处理详情查看
    const handleView = (record_id: string, sid: string): void => {
        console.log('查看详情:', record_id);
        // 导航到详情页
        navigate(`/student/${record_id}/${sid}`);
    };

    // 打开删除确认对话框
    const handleDeleteClick = (student: { id: string; record_id: string; name: string }) => {
        setStudentToDelete(student);
        setDeleteDialogOpen(true);
    };

    // 确认删除操作
    const handleDeleteConfirm = async () => {
        if (!studentToDelete) return;

        try {
            setLoading(true);
            setDeleteDialogOpen(false);

            // 调用删除API
            await deleteStudent({
                record_id: studentToDelete.record_id
            });

            // 显示成功消息
            setSnackbarSeverity('success');
            setSnackbarMessage(`学生 ${studentToDelete.name} 已成功删除`);
            setSnackbarOpen(true);

            // 重新加载数据
            loadData(searchParams);
        } catch (error) {
            console.error('删除学生失败:', error);
            setSnackbarSeverity('error');
            setSnackbarMessage('删除学生失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            setLoading(false);
            setStudentToDelete(null);
        }
    };

    // 取消删除
    const handleDeleteCancel = () => {
        setDeleteDialogOpen(false);
        setStudentToDelete(null);
    };

    // 处理分页变化
    const handlePageChange = (_event: unknown, newPage: number) => {
        setPage(newPage);
        loadData({
            ...searchParams,
            page: newPage
        });
    };

    // 创建文件输入引用
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 处理上传
    const handleUpload = () => {
        // 触发隐藏的文件输入点击事件
        fileInputRef.current?.click();
    };

    // 处理文件选择
    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];
        console.log('选择的文件:', file.name);

        // 验证文件类型
        const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();

        if (fileExtension !== '.xlsx') {
            // 显示错误提示
            setSnackbarSeverity('error');
            setSnackbarMessage('文件类型不支持，请选择Excel文件(.xlsx格式)');
            setSnackbarOpen(true);
            event.target.value = '';
            return;
        }

        // 显示上传中提示
        setSnackbarSeverity('info');
        setSnackbarMessage('正在上传文件...');
        setSnackbarOpen(true);
        setLoading(true);

        try {
            // 获取当前登录用户ID，这里假设从 localStorage 中获取
            const uid = localStorage.getItem('uid') || '1';

            // 调用上传API
            await uploadStudentFile(uid, file);

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage('学生信息文件上传成功');
            setSnackbarOpen(true);

            // 重新加载数据
            loadData(searchParams);
        } catch (error) {
            console.error('上传文件失败:', error);
            setSnackbarSeverity('error');
            setSnackbarMessage('上传文件失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            setLoading(false);
            // 重置文件输入，允许选择相同文件
            event.target.value = '';
        }
    };

    // 处理Snackbar关闭
    const handleSnackbarClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }
        setSnackbarOpen(false);
    };

    // 处理下载
    const handleDownload = async () => {
        try {
            // 显示下载中提示
            setSnackbarSeverity('info');
            setSnackbarMessage('正在准备下载文件...');
            setSnackbarOpen(true);
            setLoading(true);

            // 使用当前的搜索参数下载文件
            await downloadStudentFile(searchParams);

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage('文件下载成功');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('下载文件失败:', error);
            setSnackbarSeverity('error');
            setSnackbarMessage('下载文件失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Box className="student-page">
            {/* 隐藏的文件输入元素 */}
            <input
                type="file"
                ref={fileInputRef}
                style={{ display: 'none' }}
                onChange={handleFileChange}
                accept=".xlsx"
            />
            {/* 面包屑和操作按钮 */}
            <Box
                className="page-header"
                sx={{ display: 'flex', justifyContent: 'space-between', mb: 2, alignItems: 'center' }}>
                {/* 面包屑 */}
                <Breadcrumb items={breadcrumbItems} />

                {/* 上传和下载按钮 */}
                <Stack direction="row" spacing={1}>
                    {/* <PermissionGuard requireEditFeatures>
                        <Button variant="outlined" startIcon={<UploadIcon />} onClick={handleUpload} size="small">
                            上传
                        </Button>
                    </PermissionGuard> */}
                    <Button variant="outlined" startIcon={<DownloadIcon />} onClick={handleDownload} size="small">
                        下载
                    </Button>
                </Stack>
            </Box>

            {/* 搜索区域 - 使用新组件 */}
            <SearchForm
                initialSearchParams={searchParams}
                enrollmentStatusOptions={enrollmentStatusOptions}
                enrollmentTypeOptions={enrollmentTypeOptions}
                advisorOptions={advisorOptions}
                onSearch={handleSearch}
            />

            {/* 添加按钮 */}
            <Box className="add-button">
                <PermissionGuard requireEditFeatures>
                    <Button variant="contained" color="primary" onClick={handleAdd} startIcon={<AddIcon />}>
                        添加
                    </Button>
                </PermissionGuard>
            </Box>

            {/* 数据表格和添加按钮 */}
            <Box className="table-container" sx={{ position: 'relative', mb: 2 }}>
                <TableContainer component={Paper} variant="outlined">
                    <Table sx={{ minWidth: 650 }} aria-label="学生信息表">
                        <TableHead>
                            <TableRow>
                                <TableCell align="center" width={80}>
                                    序号
                                </TableCell>
                                <TableCell align="center">学号</TableCell>
                                <TableCell align="center">姓名</TableCell>
                                <TableCell align="center">专业</TableCell>
                                <TableCell align="center">招生类型</TableCell>
                                <TableCell align="center">毕业年份</TableCell>
                                <TableCell align="center">未来计划</TableCell>
                                <TableCell align="center">GPA</TableCell>
                                <TableCell align="center">联系方式</TableCell>
                                <TableCell align="center">顾问</TableCell>
                                <TableCell align="center">特需生</TableCell>
                                <TableCell align="center">Offer情况</TableCell>
                                <TableCell align="center" width={160}>
                                    选项
                                </TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {loading ? (
                                <TableRow key="loading-row">
                                    <TableCell colSpan={7} align="center" sx={{ py: 3 }}>
                                        <CircularProgress size={40} />
                                    </TableCell>
                                </TableRow>
                            ) : data.length > 0 ? (
                                data.map((row) => (
                                    <TableRow key={row.seq}>
                                        <TableCell align="center">{row.seq}</TableCell>
                                        <TableCell align="center">{row.sid}</TableCell>
                                        <TableCell align="center">{row.name}</TableCell>
                                        {/* <TableCell align="center">{row.college}</TableCell> */}
                                        <TableCell align="center">{row.major}</TableCell>
                                        {/* <TableCell align="center">{row.grade}</TableCell> */}
                                        <TableCell align="center">{row.approach}</TableCell>
                                        <TableCell align="center">{row.graduation_year}</TableCell>
                                        <TableCell align="center">{row.graduate_plan}</TableCell>
                                        <TableCell align="center">{row.cgpa}</TableCell>
                                        <TableCell align="center">{row.phone}</TableCell>
                                        <TableCell align="center">{row.partner}</TableCell>
                                        <TableCell align="center">{row.is_difficulty}</TableCell>
                                        <TableCell align="center">{row.is_offer}</TableCell>
                                        <TableCell align="center">
                                            <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
                                                <Button
                                                    size="small"
                                                    onClick={() => handleView(row.record_id, row.sid)}
                                                    className="action-button"
                                                    variant="contained">
                                                    详情
                                                </Button>
                                                <PermissionGuard requireEditFeatures>
                                                    <Button
                                                        size="small"
                                                        onClick={() =>
                                                            handleDeleteClick({
                                                                id: row.sid,
                                                                record_id: row.record_id,
                                                                name: row.name
                                                            })
                                                        }
                                                        className="action-button"
                                                        variant="outlined"
                                                        color="error">
                                                        删除
                                                    </Button>
                                                </PermissionGuard>
                                            </Box>
                                        </TableCell>
                                    </TableRow>
                                ))
                            ) : (
                                <TableRow key="no-data-row">
                                    <TableCell colSpan={7} align="center" className="no-data" sx={{ py: 3 }}>
                                        <Typography variant="body1" color="text.secondary">
                                            暂无数据
                                        </Typography>
                                    </TableCell>
                                </TableRow>
                            )}
                        </TableBody>
                    </Table>
                </TableContainer>
            </Box>

            {/* 分页 */}
            <Box className="pagination-container" sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2, mb: 2 }}>
                <Pagination
                    count={Math.ceil(total / rowsPerPage)}
                    page={page}
                    onChange={handlePageChange}
                    color="primary"
                    showFirstButton
                    showLastButton
                />
            </Box>

            {/* 确认删除对话框 */}
            <Dialog
                open={deleteDialogOpen}
                onClose={handleDeleteCancel}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description">
                <DialogTitle id="alert-dialog-title">确认删除</DialogTitle>
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        {studentToDelete
                            ? `确定要删除学生 ${studentToDelete.name}(${studentToDelete.id}) 的信息吗？此操作不可恢复。`
                            : '确定要删除该学生信息吗？此操作不可恢复。'}
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleDeleteCancel} color="primary">
                        取消
                    </Button>
                    <Button onClick={handleDeleteConfirm} color="error" autoFocus>
                        确认删除
                    </Button>
                </DialogActions>
            </Dialog>

            {/* 提示消息 */}
            <Snackbar open={snackbarOpen} autoHideDuration={6000} onClose={handleSnackbarClose}>
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>

            {/* 添加学生对话框 */}
            <AddStudentDialog
                open={addDialogOpen}
                onClose={() => setAddDialogOpen(false)}
                onSubmit={handleStudentSubmit}
                enrollmentStatusOptions={enrollmentStatusOptions}
                enrollmentTypeOptions={enrollmentTypeOptions}
                advisorOptions={advisorOptions}
            />
        </Box>
    );
};

export default Student;
